#include "ga.h"
#include "qdebug.h"

GA::GA(QObject *parent):QObject(parent)
{
    state = UNINITIALIZED;
    currentCost = 0;
    full=false;
}

void GA::start()
{
    history.clear();
    Population::cProb = cProb;
    Population::mProb = mProb;
    Population::rRate = rRate;
    m_pop = Population::generate(popSize);  // 生成初始种群
    m_pop.sort();
    currentCost = gCurrent = 0;
    //
    for (gCurrent = 0;  // 初始种群为第0代
         full||         // 若要求迭代至饱和，直接继续循环
         (gCurrent <= gMax); // 否则，迭代至设定的遗传代数
         gCurrent++) {

        if(gCurrent%(popSize>125?100:200) == 0) { // 每100或200代更新一次当前种群信息及最优路径
            emit update();
        }
        currentCost = m_pop.first().cost;
        history.append(currentCost);    // 记录每一代的最小代价
        if(gCurrent>=gFull&&history.at(gCurrent-gFull)==currentCost){    // 判断达到饱和条件
            break;
        }
        m_pop = m_pop.propagate();
    }
    emit update();
}
